<?php
/**
 * epg
 * 节目单
 * @author Administrator
 * @version
 */
class Model_Tables_Epg extends Zend_Db_Table_Abstract {
    /**
     * The default table name
     */
    protected $_name = 'epg';
    
    public function add( $params )
    {
        $data = array(
		'contentid' => $params['contentid'],
		'title' => $params['title'],
		//'img' => $params['img'],
		'description' => $params['description'],
		'start' => $params['start'],
		'end' => $params['end'],
		'isneedsave' => $params['isneedsave'],
		'savestatus' => $params['savestatus'],
		//'savecontentid' => $params['savecontentid'],
		//'savepath' => $params['savepath'],
        );
        return $this->insert($data);
    }
    public function modify( $params, $epgid )
    {
        $data = array(
		//'contentid' => $params['contentid'],
		'title' => $params['title'],
		//'img' => $params['img'],
		'description' => $params['description'],
		'start' => $params['start'],
		'end' => $params['end'],
		//'isneedsave' => $params['isneedsave'],
		//'savestatus' => $params['savestatus'],
		//'savecontentid' => $params['savecontentid'],
		//'savepath' => $params['savepath'],
        );
        $where = 'epgid = '.$epgid ;
        return $this->update($data , $where );
    }
    public function modifyAjax( $epgid, $field, $value )
    {
    	$data = array($field => $value);
        $where = 'epgid = '.$epgid;
        return $this->update($data , $where );
    }
    public function modifyAjaxRevers( $field ,$pri)
    {
    	$db = $this->getAdapter();
    	$sql = "update epg set  $field =not  $field  where epgid=' $pri'";
		return $db->query($sql);
    }
    public function del( $epgid )
    {
     	$where = 'epgid = '.$epgid;
        return $this->delete($where);
    }
    public function getInfo($epgid)
    {
        $row = $this->fetchRow('epgid = ' . $epgid);
        if (!$row) {
        	return null;
        }
        else
        {
        	return $row->toArray();
        }
    }
    public function getCount($s = "",$contentid =-1,$d=0)
    { 
    	$contentid = intval($contentid);
    	$db = $this->getAdapter();    	
        $select = $this->select()->from($this->_name,'count(*) as num');
        $where = $db->quoteInto(" contentid=?", $contentid);
        if($s!="")  
    	{
			$where.= " and ".$db->quoteInto("  DATEDIFF(?,start) between 0 and $d", $s);
    	}
    	$select = $select->where($where);
        $result = $this->fetchRow($select)->num;
        return $result;
    }
    public function getList($page, $numPerPage = 10,$s= "",$contentid =-1,$d=0)
    {
    	$contentid = intval($contentid);
    	$db = $this->getAdapter();
    	$page = (1>$page) ? 1 : $page;
    	$offset = ($page-1)*$numPerPage;
        $orderby = array('epgid');
        $where = $db->quoteInto(" contentid=?", $contentid);
        if($s!="")     
		{
			$where.= " and ".$db->quoteInto("  DATEDIFF(?,start) between 0 and $d", $s);
		}
        $result = $this->fetchAll($where,$orderby, $numPerPage, $offset )->toArray();
        return $result;
    }
    /**
     * 根据天数获取列表
     * 内容编号，日期，天数
     * */
    public function getListByDay($contentid =-1,$d,$index=1){
    	if(!$d)
                $d=date('Y-m-d',time());
    	$previndex = $index-1;
    	$contentid = intval($contentid);
    	$db = $this->getAdapter();
    	//$orderby = array('epgid');
    	//$where = $db->quoteInto(" contentid=?", $contentid);
    	//$where.= " and ".$db->quoteInto("  DATEDIFF(?,start) between $previndex and $index ", $d);
    	//$result = $this->fetchAll($where,$orderby)->toArray();
    	$result = $db->fetchAll("select * from epg where contentid='$contentid' and DATEDIFF('$d',start) = $previndex order by start");
        
    	$d1=date('Y-m-d',strtotime($d)-$previndex*24*60*60);
    	if(count($result)==0){
        	$result = array(
        				array("title"=>"00:00-02:00","flag"=>"0","start"=>$d1." 00:00:00","end"=>$d1." 01:59:59"),
        				array("title"=>"02:00-04:00","flag"=>"0","start"=>$d1." 02:00:00","end"=>$d1." 03:59:59"),
        				array("title"=>"04:00-06:00","flag"=>"0","start"=>$d1." 04:00:00","end"=>$d1." 05:59:59"),
        				array("title"=>"06:00-08:00","flag"=>"0","start"=>$d1." 06:00:00","end"=>$d1." 07:59:59"),
        				array("title"=>"08:00-10:00","flag"=>"0","start"=>$d1." 08:00:00","end"=>$d1." 09:59:59"),
        				array("title"=>"10:00-12:00","flag"=>"0","start"=>$d1." 10:00:00","end"=>$d1." 11:59:59"),
        				array("title"=>"12:00-14:00","flag"=>"0","start"=>$d1." 12:00:00","end"=>$d1." 13:59:59"),
        				array("title"=>"14:00-16:00","flag"=>"0","start"=>$d1." 14:00:00","end"=>$d1." 15:59:59"),
        				array("title"=>"16:00-18:00","flag"=>"0","start"=>$d1." 16:00:00","end"=>$d1." 17:59:59"),
        				array("title"=>"18:00-20:00","flag"=>"0","start"=>$d1." 18:00:00","end"=>$d1." 19:59:59"),
        				array("title"=>"20:00-22:00","flag"=>"0","start"=>$d1." 20:00:00","end"=>$d1." 21:59:59"),
        				array("title"=>"22:00-23:59","flag"=>"0","start"=>$d1." 22:00:00","end"=>$d1." 23:59:59"),
       		);
        }
    	return $result;
    }
    
    /*
     * 节目单录制操作
     */
    public function record($params,$epgid,$userinfo)
    {
    	//更新epg状态，保存点播文件，并增加到专题
    	$db = $this->getAdapter();
    	$start = $params["start"];
    	$end = $params["end"];
    	$title = $params["title"]."(".$start.")";
    	$catid = $params["cat"];
    	$special = $params["special"];
    	$spid = $userinfo["spid"];
    	
    	$options = $GLOBALS['application']->getOptions();
    	$recsite = $options["recsite"];//中低码流录制路径
    	$rechighsite = $options["rechighsite"];//高码流录制路径
    	
    	$catsql = $db->quoteInto("select model.tablename from category left join model on category.modelid = model.modelid where catid = ?",$catid);
    	$tablename = $db->fetchOne($catsql);
    	if(!$tablename)return;
    	//更新epg状态
    	$updatesql = $db->quoteInto("update epg set isneedsave = 1 where epgid = ? ",$epgid);
    	//插入点播内容
    	$insertcontentdata = array($catid,$title,$title,2,$spid,'system',time(),time(),0,1,$tablename);  
    	$insertcontentsql = $db->quoteInto("insert into content (catid, title, keywords, status, userid, username, inputtime,updatetime, isonline, contenttype,tablename) values (?)",$insertcontentdata);
    	$db->beginTransaction();
		try {
			$db->query($updatesql);
		    $db->query($insertcontentsql);
		    $contentid = $db->lastInsertId();
		    $subpath = (int)($contentid / 500);
		    $prepath = $userinfo["spid"]."/$subpath/$contentid";  //存储路径 	
		    $insertextenddata = array($contentid, $title,$recsite.$prepath."_low.flv" , $recsite.$prepath."_medium.flv", $rechighsite.$prepath."_high.flv", 2, 0, $start, $end); 
		    $insertextendsql = $db->quoteInto("insert into $tablename(contentid, content, urllow, urlmedium, urlhigh, vodtype, mediatype, starttime, endtime) values (?)",$insertextenddata);	    
		    $db->query($insertextendsql);
		    $updatesql = $db->quoteInto("update epg set savecontentid = '$contentid',savepath = '$prepath', isneedsave = 1 where epgid = ? ",$epgid);
		    $db->query($updatesql);
		    $db->commit();
		} catch (Exception $e) {
			$db->rollBack();
		    return false;
		}
		return true;
    }
    
    public function mark($params,$epgid,$userinfo)
    {
    	//更新epg状态，保存点播文件，并增加到专题
    	//print_r($params);exit;
    	//print_r($userinfo);exit;
    	$db = $this->getAdapter();
    	$btnmarkrecord = $params["btnmarkrecord"];//标注后是否录制
    	$start = $params["start"];
    	$end = $params["end"];
    	$markstart = $params["markstart"];
    	$markend = $params["markend"];
    	
    	$title = $params["title"];
    	$catid = $params["cat"];
    	$special = $params["special"];
    	
    	$spid = $userinfo["spid"];
    	$options = $GLOBALS['application']->getOptions();
    	$recsite = $options["recsite"];//中低码流录制路径
    	$rechighsite = $options["rechighsite"];//高码流录制路径
    	
    	$catsql = $db->quoteInto("select model.tablename from category left join model on category.modelid = model.modelid where catid = ?",$catid);
     	$tablename = $db->fetchOne($catsql);
    	if(!$tablename)return;
    	//插入epgmark数据
    	$isneedsave = 0;
    	$vodtype = 1;
    	//插入点播内容
    	$insertcontentdata = array($catid,$title,$title,99,$spid,'system',time(),time(),1,1,$tablename); //标注节目
    	if($btnmarkrecord)//录制
    	{
    		$isneedsave=1;
    		$vodtype = 2;
    		$insertcontentdata = array($catid,$title,$title,2,$spid,'system',time(),time(),0,1,$tablename); //录制节目
    	}else{
    		$start = $markstart;
    		$end = strtotime($markstart) + (3 * 24 * 60 * 60);
    		$end = date("Y-m-j H:i:s",$end);
    	}
    	$insertcontentsql = $db->quoteInto("insert into content (catid, title, keywords, status, userid, username, inputtime,updatetime, isonline, contenttype,tablename) values (?)",$insertcontentdata);
    	$db->beginTransaction();
		try {
			//$db->query($updatesql);
		    $db->query($insertcontentsql);
		    $contentid = $db->lastInsertId();
		    $subpath = (int)($contentid / 500);
		    $prepath = $userinfo["spid"]."/$subpath/$contentid";  //存储路径 	
		    $insertextenddata = array($contentid, $title,$recsite.$prepath."_low.flv" , $recsite.$prepath."_medium.flv", $rechighsite.$prepath."_high.flv", $vodtype, 0, $start, $end); 
		    $insertextendsql = $db->quoteInto("insert into $tablename(contentid, content, urllow, urlmedium, urlhigh, vodtype, mediatype, starttime, endtime) values (?)",$insertextenddata);	    
		    $db->query($insertextendsql);
		   	$insertsql = "insert into epgmark ( epgid, contentid, title, img, description, start, end, isneedsave, savestatus, savecontentid, savepath)
			select epgid, contentid, title, img, description, '$markstart', '$markend', '$isneedsave', '0', '$contentid', '$prepath' from epg where epgid = '$epgid'";
		    $db->query($insertsql);
		    //插入专题
		    $specials = explode(",",$special);
		    foreach($specials as $s)
		    {
		    	if($s>0)
		    	{
		    		$params = array("specialid"=>$s,"contentid"=>$contentid,"listorder"=>$contentid,"contenttype"=>"2");
		    		$db->query("insert into special_content(specialid,contentid,contenttype,listorder) values(:specialid,:contentid,:contenttype,:listorder)",$params);
				}
		    }		    
		    $db->commit();
		} catch (Exception $e) {
			$db->rollBack();
			print_r($e);exit;
		    return false;
		}
		return true;
    }
	/*
	 * 根据模型类型获取栏目
	 */
	public function getCategoryNameList($modeltype)
	{
		$db = $this->getAdapter();
		$select = $db->quoteInto("select concat(arrparentid,',',catid) as step,catid, catname from category left join model on category.modelid = model.modelid where model.modeltype =?", $modeltype);
		$result = $db->query($select);
    	$cats = array();
        if (!empty($result))
	        {
	            foreach ($result as $item)
	            {
	                $cats[$item['catid']] = $item['catname'];
	            }
	        }
        return $cats;
	}
	/*
	 * 根据名称获取专题数组
	 */
	public function getSpecialsByName($name)
	{
		$db = $this->getAdapter();
		$select = $db->quoteInto("select contentid, title from content where contenttype = 2 and title like ? limit 0, 50","%$name%");
		$result = $db->query($select);
		$specials = "";
        if (!empty($result))
	        {
	            foreach ($result as $item)
	            {
	            	$specials .= $item['contentid']."|".$item['title']."\n";
	            }
	        }
        return $specials;
	}
	public function getTvStations($imgsite)
	{
		$db = $this->getAdapter();
		$select = "select iconorder, tumblow from content where contenttype = 0 and isonline = 1 order by iconorder";
		$result = $db->query($select);
		$tvstation = array();
        if (!empty($result))
	        {
	            foreach ($result as $item)
	            {
	            	$tvstation[$item['iconorder']] = $imgsite.$item['tumblow']."?t=".time(date());;
	            }
	        }
        return $tvstation;
	}
}